Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Java 8 Interview Questions and Answers

Question: What Is a Default Method and When Do We Use It?
Answer:
A default method is a method with an implementation – which can be found in an interface.
We can use a default method to add a new functionality to an interface while maintaining backward compatibility with classes that are already implementing the interface:
public interface CarBehaviour {
    public void move();
    default void peep() {
        System.out.println("peep!");
    }
}
Usually, when a new abstract method is added to an interface, all implementing classes will break until they implement the new abstract method. In Java 8, this problem has been solved by the use of default method.
For example, Collection interface does not have forEach method declaration. Thus, adding such method would simply break the whole collections API.
Java 8 introduces default method so that Collection interface can have a default implementation of forEach method without requiring the classes implementing this interface to implement the same.
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook